package com.lbiuse.wx.bean.pay;

import com.lbiuse.wx.bean.Status;
import com.lbiuse.wx.util.MD5Util;
import com.lbiuse.wx.util.WechatConfigUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.TreeMap;

@Data
@Slf4j
public class PrePayResult extends Status {
    private String return_code;//
    private String return_msg;//
    private String appid;//
    private String mch_id;//
    private String device_info;//
    private String nonce_str;//
    private String sign;//
    private String result_code;//
    private String err_code_des;//

    private String trade_type;//
    private String prepay_id;//
    private String code_url;//

    public boolean checkSign() throws Exception {


        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("return_code", this.result_code);
        treeMap.put("return_msg", this.return_msg);
        treeMap.put("appid", this.appid);
        treeMap.put("mch_id", this.mch_id);
        treeMap.put("device_info", this.device_info);
        treeMap.put("nonce_str", this.nonce_str);
        treeMap.put("result_code", this.result_code);
        treeMap.put("err_code_des", this.err_code_des);
        treeMap.put("trade_type", this.trade_type);
        treeMap.put("prepay_id", this.prepay_id);

        treeMap.put("code_url", this.code_url);


        StringBuilder sb = new StringBuilder();
        for (String key : treeMap.keySet()) {
            if (StringUtils.isNotEmpty(treeMap.get(key))) {
                sb.append(key).append("=").append(treeMap.get(key)).append("&");
            }
        }
        sb.append("key=" + WechatConfigUtil.getShopSecrect());
        log.debug(sb.toString());
        String sign = MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
        if (sign.equals(this.sign)) {
            return true;
        } else {
            log.debug("prePayResult sign error :{}", this);
            return false;
        }
    }
}
